package com.maxdu.labs.stt.fragments;

import java.util.ArrayList;
import java.util.List;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.example.stt.R;
import com.facebook.Request;
import com.facebook.Response;
import com.facebook.Session;
import com.facebook.SessionState;
import com.facebook.UiLifecycleHelper;
import com.facebook.model.GraphUser;
import com.facebook.widget.ProfilePictureView;
import com.maxdu.labs.stt.STTApplication;
import com.maxdu.labs.stt.activities.PickerActivity;
import com.maxdu.labs.stt.constants.Constants;
import com.maxdu.labs.stt.models.User;
import com.maxdu.labs.stt.utils.FriendRequestUtils;

public class SelectionFragment extends Fragment {

	private static final int REAUTH_ACTIVITY_CODE = 100;
	
	private ProfilePictureView profilePictureView;
	private TextView userNameView;
	private Button inviteButton;
	private ListView listViewFriendsToInvite;
	private List<User> listFriendsToInvite;
	private String currentUser;
	
	private List<GraphUser> selectedUsers;
	
	@Override
	public View onCreateView(LayoutInflater inflater,
			@Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
		
		super.onCreateView(inflater, container, savedInstanceState);
	    View view = inflater.inflate(R.layout.selection, 
	            container, false);
	    
	 // Find the user's profile picture custom view
	    profilePictureView = (ProfilePictureView) view.findViewById(R.id.selection_profile_pic);
	    profilePictureView.setCropped(true);

	    userNameView = (TextView) view.findViewById(R.id.selection_user_name);
	    listViewFriendsToInvite = (ListView) view.findViewById(R.id.listFriendsToInvite);
	    listFriendsToInvite = new ArrayList<User>();
	    // Set the list view adapter
	    listViewFriendsToInvite.setAdapter(new FriendToInviteAdapter(getActivity(), R.id.listFriendsToInvite, listFriendsToInvite));

	    TextView inviteFriendsTextV = (TextView) view.findViewById(R.id.invite_friends);
	    inviteFriendsTextV.setOnClickListener(new OnClickListener(){
	        
	            @Override
	            public void onClick(View view) {
	            	startPickerActivity(PickerActivity.FRIEND_PICKER, 0);
	            }
	    });
	    
	    //find the "Invite" button and hide it
	    inviteButton = (Button) view.findViewById(R.id.inviteBtn);
	    inviteButton.setVisibility(View.GONE);
	    
	 // Check for an open session
	    Session session = Session.getActiveSession();
	    if (session != null && session.isOpened()) {
	    	
	        // Get the user's data
	        makeMeRequest(session);
	    }

	    return view;
	}

	/**
	First, create a private method that requests the user's data:
	**/
	private void makeMeRequest(final Session session) {
	    // Make an API call to get user data and define a 
	    // new callback to handle the response.
	    Request request = Request.newMeRequest(session, 
	            new Request.GraphUserCallback() {
	        @Override
	        public void onCompleted(GraphUser user, Response response) {
	            // If the response is successful
	            if (session == Session.getActiveSession()) {
	                if (user != null) {
	                    // Set the id for the ProfilePictureView
	                    // view that in turn displays the profile picture.
	                    profilePictureView.setProfileId(user.getId());
	                    // Set the Textview's text to the user's name.
	                    userNameView.setText(user.getName());
	                    currentUser = user.getId();
	                }
	            }
	            if (response.getError() != null) {
	                // Handle errors, will do so later.
	            }
	        }
	    });
	    request.executeAsync();
	} 
	
	/**
	Next, define a private method that will respond to session changes and call the makeMeRequest() method 
	if the session's open:
	**/
	private void onSessionStateChange(final Session session, SessionState state, Exception exception) {
	    if (session != null && session.isOpened()) {
	        // Get the user's data.
	        makeMeRequest(session);
	        Log.w(Constants.LOG_TAG,"SelectionFragment::onSessionStateChange ==> session is OPENED");
	    }
	}
	
	/**
	 * 
	 * Now that you've set up the response to session state changes, you can set up a UiLifecycleHelper 
	 * instance and an associated listener that will call the onSessionStateChange() method.
		Define private variables for the UiLifecycleHelper object and the Session.StatusCallback listener 
		implementation. The listener overrides the call() method to invoke the onSessionStateChange() method you previously defined:
	 */
	
	private UiLifecycleHelper uiHelper;
	private Session.StatusCallback callback = new Session.StatusCallback() {
	    @Override
	    public void call(final Session session, final SessionState state, final Exception exception) {
	        onSessionStateChange(session, state, exception);
	    }
	};

	/**
	 Next, override the onCreate() method to initialize the UiLifecycleHelper object and call it's onCreate() method:
	 **/
	@Override
	public void onCreate(Bundle savedInstanceState) {
	    super.onCreate(savedInstanceState);
	    uiHelper = new UiLifecycleHelper(getActivity(), callback);
	    uiHelper.onCreate(savedInstanceState);
	}
	
	
	
	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
	    super.onActivityResult(requestCode, resultCode, data);
	    if (requestCode == REAUTH_ACTIVITY_CODE) {
	      uiHelper.onActivityResult(requestCode, resultCode, data);
	    } else if (resultCode == Activity.RESULT_OK) {
	        selectedUsers = ((STTApplication) getActivity()
	                 .getApplication())
	                 .getSelectedUsers();

	        updateListViewFriendToInvite(selectedUsers);

          //show up the inviteBtn
	        initializeInviteBtn();
	    }
	}
	
	@Override
	public void onResume() {
	    super.onResume();
	    uiHelper.onResume();
	}

	@Override
	public void onSaveInstanceState(Bundle bundle) {
	    super.onSaveInstanceState(bundle);
	    uiHelper.onSaveInstanceState(bundle);
	}

	@Override
	public void onPause() {
	    super.onPause();
	    uiHelper.onPause();
	}

	@Override
	public void onDestroy() {
	    super.onDestroy();
	    uiHelper.onDestroy();
	}
	
	private class FriendToInviteAdapter extends ArrayAdapter<User> {
	    private List<User> listFriendsToInvite;

	    public FriendToInviteAdapter(Context context, int resourceId, List<User> listFriendsToInvite) {
	        super(context, resourceId, listFriendsToInvite);
	        this.listFriendsToInvite = listFriendsToInvite;
	    }

	    @Override
	    public View getView(int position, View convertView, ViewGroup parent) {
	        View view = convertView;
	        if (view == null) {
	            LayoutInflater inflater =
	                    (LayoutInflater) getActivity()
	                    .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
	            view = inflater.inflate(R.layout.row_friendtoinvite, parent,false);
	        }

	        User friendToInvite = listFriendsToInvite.get(position);
	        if (friendToInvite != null) {
	            TextView nameTextV = (TextView) view.findViewById(R.id.friendtoinvite_name);
	            ProfilePictureView profilePictureView = (ProfilePictureView)view.findViewById(R.id.friendtoinvite_picture);
	            profilePictureView.setProfileId(friendToInvite.getUserId());

	            if (nameTextV != null) {
	            	nameTextV.setText(friendToInvite.getName());
	            }
	        }
	        
	        return view;
	    }
	}
	
	private void updateListViewFriendToInvite(List<GraphUser> listFriendsToInviteGU){
	    	
	    	List<User> listFriendsToInvite = convertFromGUToFTI(listFriendsToInviteGU);
	    	
	    	listViewFriendsToInvite.setAdapter(new FriendToInviteAdapter(getActivity(), R.id.listFriendsToInvite, listFriendsToInvite));
	    }
	    
	    private List<User> convertFromGUToFTI(List<GraphUser> listFriendsToInviteGU){
	    	List<User> listFriendToInvite = new ArrayList<User>();
	    	if (listFriendsToInviteGU != null){
	    		for (GraphUser gu : listFriendsToInviteGU){
	    			listFriendToInvite.add(new User(gu.getId(), gu.getName()));
	    		}
	    	}
	    	return listFriendToInvite;
	    }
	    
		private void startPickerActivity(Uri data, int requestCode) {
		     Intent intent = new Intent();
		     intent.setData(data);
		     intent.setClass(getActivity(), PickerActivity.class);
		     startActivityForResult(intent, requestCode);
		 }

	    private void initializeInviteBtn(){
	    	if (selectedUsers != null && selectedUsers.size() > 0){
		    	inviteButton.setVisibility(View.VISIBLE);
		    	inviteButton.setOnClickListener(new OnClickListener() {           

		    		  @Override
		    		  public void onClick(View v) 
		    		  {
		    		      Toast.makeText(v.getContext(), "Friends invited!", Toast.LENGTH_LONG).show();
		    		      listFriendsToInvite = convertFromGUToFTI(selectedUsers);
		    		      FriendRequestUtils.sendRequest(currentUser, listFriendsToInvite);
		    		  }    
		    		});
		    }
	    }
}
